const app = getApp()

Page({
  data: {
    currentTab: 'total',
    tabList: [
      { key: 'total', name: '总榜' },
      { key: 'month', name: '月榜' },
      { key: 'week', name: '周榜' }
    ],
    rankList: [],
    myRank: null,
    page: 1,
    perPage: 20,
    hasMore: true,
    loading: false
  },

  onLoad() {
    this.loadLeaderboard()
  },

  onShow() {
    // 页面显示时刷新数据
    this.refreshData()
  },

  onPullDownRefresh() {
    this.refreshData()
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMore()
    }
  },

  // 切换排行榜类型
  switchTab(e) {
    const tabKey = e.currentTarget.dataset.key
    if (tabKey === this.data.currentTab) return
    
    this.setData({
      currentTab: tabKey,
      rankList: [],
      myRank: null,
      page: 1,
      hasMore: true
    })
    
    this.loadLeaderboard()
  },

  // 加载排行榜数据
  loadLeaderboard(refresh = false) {
    if (this.data.loading) return

    this.setData({ loading: true })

    const params = {
      type: this.data.currentTab,
      page: refresh ? 1 : this.data.page,
      per_page: this.data.perPage
    }

    wx.request({
      url: `${app.globalData.baseUrl}/leaderboards/`,
      method: 'GET',
      data: params,
      header: app.globalData.token ? {
        'Authorization': `Bearer ${app.globalData.token}`
      } : {},
      success: (res) => {
        if (res.data.success) {
          const newRankList = res.data.data.items
          const total = res.data.data.total
          const currentPage = res.data.data.page
          const hasMore = currentPage * this.data.perPage < total
          const myRank = res.data.data.my_rank

          this.setData({
            rankList: refresh ? newRankList : [...this.data.rankList, ...newRankList],
            myRank: myRank,
            page: currentPage + 1,
            hasMore: hasMore,
            loading: false
          })

          if (refresh) {
            wx.stopPullDownRefresh()
          }
        } else {
          wx.showToast({
            title: res.data.message || '加载失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('加载排行榜失败:', err)
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
        this.setData({ loading: false })
        if (refresh) {
          wx.stopPullDownRefresh()
        }
      }
    })
  },

  // 加载更多
  loadMore() {
    this.loadLeaderboard()
  },

  // 刷新数据
  refreshData() {
    this.setData({
      rankList: [],
      myRank: null,
      page: 1,
      hasMore: true
    })
    this.loadLeaderboard(true)
  },

  // 跳转到考试页面
  goToExams() {
    wx.switchTab({
      url: '/pages/exams/exams'
    })
  }
}) 